package com.example.smartcity.ui.notifications.activity

import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import androidx.core.widget.addTextChangedListener
import com.example.smartcity.App.Companion.getToken
import com.example.smartcity.R
import com.example.smartcity.databinding.ActivityPersonFeedbackBinding
import com.example.smartcity.logic.Repository.api
import com.example.smartcity.logic.Repository.coroutine
import com.example.smartcity.logic.util.Util.show
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 * 个人中心-意见反馈模块
 */
class PersonFeedbackActivity : AppCompatActivity() {

    private lateinit var mBinding: ActivityPersonFeedbackBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityPersonFeedbackBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        // 显示回退按钮
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        // 设置标题
        title = "意见反馈"


        // 监听输入框内容变化， 然后获取字数更改文本显示
        mBinding.eContent.addTextChangedListener  {
            val len = it?.length.toString() + "/150"
            mBinding.TvLength.text = len
        }


        // 点击提交反馈内容
        mBinding.BtnPut.setOnClickListener {
            postContent()
        }
    }


    /**
     * 提交反馈内容
     */
    private fun postContent() = coroutine {
        // 我们就只反馈内容就可以了， 标题就不弄了
        api.getPUTFeedback(getToken, JSONObject().apply {
            put("content", mBinding.eContent.text)
        }.toString().toRequestBody("application/json".toMediaType())).apply {
            // 判断是否提交成功
            if (this.code == 200) {
                runOnUiThread {
                    "提交成功".show()
                    // 清空输入框内容
                    mBinding.eContent.setText("")
                }
            } else runOnUiThread {
                // 如果返回其他的侧提示回调信息
                this.msg?.show()
            }
        }
    }



    /**
     * 点击回退按钮消除该页面
     */
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}